//
//  ZPCourseViewController.m
//  ZPIOSEducation
//
//  Created by hh on 2016/11/23.
//  Copyright © 2016年 liwei. All rights reserved.
//

#import "ZPCourseViewController.h"
#import "ZPNextViewController.h"
#import "ZPFilterViewController.h"
#import "ZPCourseTableViewCell.h"
#import "ZPSelScCollectionViewCell.h"
#import "ZPTeacherDetailViewController.h"
#import "ComfirmOrderViewController.h"
#import "MJRefresh.h"
#import "SearchViewController.h"
#import "ZPBaseNavigationController.h"
#import "MessageViewController.h"
#import "ZPRegisterLoginViewController.h"

extern NSString  *existUnreadMsg;

@interface ZPCourseViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>{
    __weak IBOutlet UIView *switchView;
    __weak IBOutlet NSLayoutConstraint *constain1;
    __weak IBOutlet NSLayoutConstraint *constrain2;
    __weak IBOutlet NSLayoutConstraint *collectionHeight;
    MBProgressHUD *hud;
    IBOutlet UIView *titleViewC;
    __weak IBOutlet UITextField *searchT;
    __weak IBOutlet UIView *emptyView;
}

@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
@property (weak, nonatomic) IBOutlet UIButton *button3;
@property (weak, nonatomic) IBOutlet UIButton *defaultOrderBtn;

@property (strong,nonatomic) ZPFilterViewController *vc3;
@property (weak, nonatomic) IBOutlet UITableView *courseTableView;
@property (weak, nonatomic) IBOutlet UIView *selectOrderView;
@property (weak, nonatomic) IBOutlet UICollectionView *selectSchoolView;


@property (strong,nonatomic) NSMutableArray *dataArray;

@property (strong,nonatomic) NSArray *schoolDataArr;

@property (strong,nonatomic) NSMutableDictionary *paramDic;

@property (assign,nonatomic) unsigned currentRequestPageNum;
@property (assign) BOOL hasNextPage;
@property (assign) BOOL needRefreshData;
@end

@implementation ZPCourseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _needRefreshData = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshSearch" object:nil];
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(refreshNavMessageImage) name:@"changeMessageIconStatus" object:nil];

    hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:hud];
    
    _currentRequestPageNum = 1;
    _dataArray = [NSMutableArray array];
    _paramDic = [NSMutableDictionary dictionary];
    _schoolDataArr = [NSArray array];
    _defaultOrderBtn.selected=YES;
    self.navigationItem.title = @"选课";
    
    [_courseTableView registerNib:[UINib nibWithNibName:@"ZPCourseTableViewCell" bundle:nil] forCellReuseIdentifier:@"ZPCourseTableViewCell"];
    [_selectSchoolView registerNib:[UINib nibWithNibName:@"ZPSelScCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ZPSelScCollectionViewCell"];
    _courseTableView.tableFooterView=[UIView new];
    
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc ]initWithTarget:self action:@selector(hideView:)];
    [_selectOrderView addGestureRecognizer:tap];

    [self setupRefresh];
    [self getData:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self  refreshNavMessageImage];
}

- (void)refreshNavMessageImage
{
    if ([existUnreadMsg  integerValue] == 1) {
        if (_fromSearch) {
            [self setNav];
        }else{
            UIBarButtonItem *b1=[[UIBarButtonItem alloc]initWithImage:Z_IMAGE(@"Search_Icon") style:UIBarButtonItemStylePlain target:self action:@selector(showSearch)];
            
            UIButton *b=[UIButton buttonWithType:UIButtonTypeCustom];
            [b setBackgroundImage:[UIImage imageNamed:@"Message_RedPoint"] forState:UIControlStateNormal];
            [b addTarget:self action:@selector(showMessage) forControlEvents:UIControlEventTouchUpInside];
            b.bounds = CGRectMake(0, 0, 22, 22);
            UIBarButtonItem *b2=[[UIBarButtonItem alloc]initWithCustomView:b];
            self.navigationItem.rightBarButtonItems = @[b2,b1];
        }
        
    }else {
        if (_fromSearch) {
            [self setNav];
        }else{
            UIBarButtonItem *b1=[[UIBarButtonItem alloc]initWithImage:Z_IMAGE(@"Search_Icon") style:UIBarButtonItemStylePlain target:self action:@selector(showSearch)];
            UIButton *b=[UIButton buttonWithType:UIButtonTypeCustom];
            [b setBackgroundImage:[UIImage imageNamed:@"zhenpin_un_news"] forState:UIControlStateNormal];
            [b addTarget:self action:@selector(showMessage) forControlEvents:UIControlEventTouchUpInside];
            b.bounds = CGRectMake(0, 0, 22, 22);
            UIBarButtonItem *b2=[[UIBarButtonItem alloc]initWithCustomView:b];
            self.navigationItem.rightBarButtonItems = @[b2,b1];
        }
        
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"refreshSearch" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"changeMessageIconStatus" object:nil];
}

-(void)refreshData{
    _currentRequestPageNum=1;
    _needRefreshData = YES;
    [_paramDic removeAllObjects];
    if (_vc3) {
        [_vc3 clearFilter];
    }
    [_paramDic setObject:[NSString stringWithFormat:@"%u",_currentRequestPageNum] forKey:@"pagenumber"];
    [self getData:YES];
}

-(void)showSearch{
    SearchViewController  *viewController = [[SearchViewController  alloc] initWithNibName:@"SearchViewController" bundle:nil];
    ZPBaseNavigationController  *navController = [[ZPBaseNavigationController  alloc] initWithRootViewController:viewController];
    [self presentViewController:navController animated:YES completion:nil];
}

-(void)showMessage{
    if ([[ZPAuthStore  sharedZPAuthStore] isLogin]) {
        MessageViewController  *viewController = [[MessageViewController  alloc] initWithNibName:@"MessageViewController" bundle:nil];
        [self.navigationController  pushViewController:viewController animated:YES];
    }else {
        ZPRegisterLoginViewController  *viewController = [[ZPRegisterLoginViewController  alloc] initWithNibName:@"ZPRegisterLoginViewController" bundle:nil];
        ZPBaseNavigationController  *navController = [[ZPBaseNavigationController  alloc] initWithRootViewController:viewController];
        [self presentViewController:navController animated:YES completion:nil];
    }
}

-(void)setNav{

    titleViewC.frame =CGRectMake(0, 0, SCREENWIDTH-120, 30);
    searchT.text = _searchText;
    self.navigationItem.titleView = titleViewC;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    NSString  *searchStr = [textField.text  stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (searchStr.length == 0) {
        UIAlertView  *alert = [[UIAlertView  alloc] initWithTitle:@"提示" message:@"输入不正确,请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert  show];
    }else {
        _searchText = searchStr;
        [self getData:YES];
    }
    
    return YES;
}

-(void)setupRefresh{
    __weak ZPCourseViewController *weak = self;
    [_courseTableView addLegendHeaderWithRefreshingBlock:^{
        weak.currentRequestPageNum=1;
        [weak.paramDic setObject:[NSString stringWithFormat:@"%u",weak.currentRequestPageNum] forKey:@"pagenumber"];
        [weak getData:YES];
    }];
    
    
    [_courseTableView addLegendFooterWithRefreshingBlock:^{
        if (weak.hasNextPage) {
            weak.currentRequestPageNum+=1;
            [weak.paramDic setObject:[NSString stringWithFormat:@"%u",weak.currentRequestPageNum] forKey:@"pagenumber"];
            [weak getData:NO];
        }else{
            if (weak.courseTableView.footer.isRefreshing) {
                [weak.courseTableView.footer endRefreshing];
            }
            if (weak.courseTableView.header.isRefreshing) {
                [weak.courseTableView.header endRefreshing];
            }
        }

    }];
}
- (IBAction)hideView:(UITapGestureRecognizer *)sender {
    [self showOrder:_button1];
}


-(void)getDataWithFilter:(NSDictionary *)dic{
    [_paramDic addEntriesFromDictionary:dic];
    _currentRequestPageNum=1;
    [_paramDic removeObjectForKey:@"pagenumber"];
    [self getData:YES];
}

-(void)resetFilter:(NSArray *)key{
    [_paramDic removeObjectsForKeys:key];
    _currentRequestPageNum=1;
    [_paramDic removeObjectForKey:@"pagenumber"];
}

-(void)getData:(BOOL)remove{
    [hud showAnimated:YES];
    
    [_paramDic setObject:NU([[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"cityId"]) forKey:@"cityId"];
    
    if (_searchText) {
        if (_searchText.length>0) {
            [_paramDic setObject:_searchText forKey:@"searchText"];
        }
    }
    
    [_paramDic setObject:NU([[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"grade"]) forKey:@"currentGrade"];
    
    if ([_paramDic.allKeys containsObject:@"classYear"]) {
        if ([[_paramDic objectForKey:@"classYear"] isEqualToString:@"全部"]) {
            [_paramDic removeObjectForKey:@"classYear"];
        }
    }
    
    [[ZPNetworking sharedZPNetworking] GET:APISearch@"search/teacherSearchForSift.json"
                                 parameters:_paramDic progress:nil success:^(id  _Nonnull responseObject) {
                                     [hud hideAnimated:YES];
                                     if (_courseTableView.footer.isRefreshing) {
                                         [_courseTableView.footer endRefreshing];
                                     }
                                     if (_courseTableView.header.isRefreshing) {
                                         [_courseTableView.header endRefreshing];
                                     }
                                     if (CodeIs200(responseObject)) {
                                         
                                         _currentRequestPageNum = [[[[responseObject objectForKey:@"result"] objectForKey:@"page"] objectForKey:@"lastPageNumber"] unsignedIntValue];
                                         
                                         if (remove) {
                                             [_dataArray removeAllObjects];
                                         }
                                         
                                         [_dataArray  addObjectsFromArray:[[[responseObject objectForKey:@"result"] objectForKey:@"page"] objectForKey:@"result"]];
                                         
                                         if (_dataArray.count) {
                                             emptyView.hidden=YES;
                                             _courseTableView.hidden=NO;
                                         }else{
                                             emptyView.hidden=NO;
                                             _courseTableView.hidden=YES;
                                         }
                                         
                                         
                                         _hasNextPage = [[[[responseObject objectForKey:@"result"] objectForKey:@"page"] objectForKey:@"hasNextPage"] boolValue];
                                         
                                         if (!_hasNextPage) {
                                             [_courseTableView.footer noticeNoMoreData];
                                         }else{
                                             [_courseTableView.footer resetNoMoreData];
                                         }
                                         
                                         
                                         [_courseTableView reloadData];
                                         
                                         
                                         
                                         
                                         
                                         NSDictionary *result = [responseObject objectForKey:@"result"];
                                         
                                         
                                         if (_needRefreshData) {
                                             _needRefreshData = NO;
                                             NSMutableArray *arr = [[[result objectForKey:@"parameter"] objectForKey:@"schoolTree"] mutableCopy];
                                             [arr insertObject:@{@"schoolId":@"",@"schoolName":@"全部"} atIndex:0];
                                             _schoolDataArr = [arr copy];
                                             collectionHeight.constant = 44* ceilf(_schoolDataArr.count/3.0);
                                             [_selectSchoolView setNeedsUpdateConstraints];
                                             [_selectSchoolView reloadData];
                                             [_selectSchoolView selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
                                         }

                                         
                                         if (![self.childViewControllers containsObject:_vc3]) {
                                             if ([result objectForKey:@"parameter"]) {
                                                 _vc3=[[ZPFilterViewController alloc]initWithParam:[[result objectForKey:@"parameter"] copy]];
                                                 __weak ZPCourseViewController *weakSelf = self;
                                                 __weak UIButton *weakButton = _button3;
                                                 [_vc3 setFilterBlock:^(NSDictionary *paramDic) {
                                                     [weakSelf showFilter:weakButton];
                                                     [weakSelf getDataWithFilter:paramDic];
                                                 }];
                                                 
                                                 [_vc3 setResetBlock:^(NSArray *arr) {
                                                     [weakSelf resetFilter:arr];
                                                 }];

                                                 [self addChildViewController:_vc3];
                                             }
                                         }

                                         
                                         
                                     }else{
                                         [_courseTableView reloadData];
                                     }
                                 } failure:^(NSError * _Nonnull error) {
                                     [_courseTableView reloadData];
                                     [hud hideAnimated:YES];
                                     if (_courseTableView.footer.isRefreshing) {
                                         [_courseTableView.footer endRefreshing];
                                     }
                                     if (_courseTableView.header.isRefreshing) {
                                         [_courseTableView.header endRefreshing];
                                     }
                                 }];
}
- (IBAction)selectorderAction:(UIButton *)sender {
    for (UIView *tmp in _selectOrderView.subviews) {
        for (UIButton *btn in tmp.subviews) {
            if ([btn isKindOfClass:[UIButton class]]) {
                btn.selected = NO;
            }
        }

    }
    sender.selected = YES;
    [_paramDic setObject:[NSString stringWithFormat:@"%li",sender.tag-2000] forKey:@"order"];
    
    _currentRequestPageNum=1;
    [_paramDic setObject:[NSString stringWithFormat:@"%u",_currentRequestPageNum] forKey:@"pagenumber"];
    [self getData:YES];
    
    
    [self showOrder:_button1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)showOrder:(UIButton *)sender {
    _button2.selected = NO;
    _button3.selected = NO;
    sender.selected=!sender.selected;
    
    constrain2.constant = 0;
    [_vc3.view removeFromSuperview];
    
    if (sender.selected) {
        [UIView animateWithDuration:0.25 animations:^{
            constain1.constant = SCREENHEIGHT - CGRectGetMaxY(switchView.frame);
            [self.view layoutIfNeeded];
            [self.view updateConstraintsIfNeeded];
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            constain1.constant = 0;
            [self.view updateConstraintsIfNeeded];
            [self.view layoutIfNeeded];
        }];
    }


}
- (IBAction)showSchoolLoc:(UIButton *)sender {
    _button1.selected = NO;
    _button3.selected = NO;
    sender.selected=!sender.selected;
    constain1.constant = 0;
    [_vc3.view removeFromSuperview];
    
    if (sender.selected) {
        [UIView animateWithDuration:0.25 animations:^{
            constrain2.constant = SCREENHEIGHT - CGRectGetMaxY(switchView.frame);
            [self.view layoutIfNeeded];
            [self.view updateConstraintsIfNeeded];
        }];
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            constrain2.constant = 0;
            [self.view updateConstraintsIfNeeded];
            [self.view layoutIfNeeded];
        }];
    }

    
}
- (IBAction)showFilter:(UIButton *)sender {
    _button1.selected = NO;
    _button2.selected = NO;
    sender.selected=!sender.selected;
    constain1.constant = 0;
    constrain2.constant = 0;
    if (sender.selected) {
        _vc3.view.frame = CGRectMake(SCREENWIDTH, 44, SCREENWIDTH, SCREENHEIGHT-93);
        [self.view addSubview:_vc3.view];
        [UIView animateWithDuration:0.25 animations:^{
            _vc3.view.frame = CGRectMake(0, 44, SCREENWIDTH, SCREENHEIGHT-93);
        }];

    }else{
        [UIView animateWithDuration:0.1 animations:^{
            _vc3.view.alpha = 0.0;
        } completion:^(BOOL finished) {
            if (finished) {
                _vc3.view.alpha = 1.0;
                [_vc3.view removeFromSuperview];
            }
        }];
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tmp = [_dataArray objectAtIndex:indexPath.row];
    ZPCourseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZPCourseTableViewCell"];
    cell.teacherName.text = toStr([tmp objectForKey:@"teacherName"]);
    cell.classCount = toStr([tmp objectForKey:@"classCount"]);
    cell.classGradeName.text = toStr([tmp objectForKey:@"classGradeName"]);
    cell.schoolName.text = toStr([tmp objectForKey:@"schoolName"]);
    cell.courseName.text = toStr([tmp objectForKey:@"courseName"]);
    cell.isFull = [[tmp objectForKey:@"isFull"] boolValue];
    [cell.headImageView sd_setImageWithURL:[tmp objectForKey:@"headUrl"] placeholderImage:[UIImage imageNamed:@"headportrait"]];
    cell.totalScore.text = [NSString stringWithFormat:@"%@分",[tmp objectForKey:@"totalScore"]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZPTeacherDetailViewController *vc=[[ZPTeacherDetailViewController alloc]init];
    vc.teacherId = toStr([[_dataArray objectAtIndex:indexPath.row] objectForKey:@"teacherId"]);
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _schoolDataArr.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZPSelScCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZPSelScCollectionViewCell" forIndexPath:indexPath];
    cell.iemLab.text = [[_schoolDataArr objectAtIndex:indexPath.row] objectForKey:@"schoolName"];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    float len=(SCREENWIDTH-6.0)/3;
    return CGSizeMake(len, 44);
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [_paramDic setObject:[[_schoolDataArr objectAtIndex:indexPath.row]objectForKey:@"schoolId"] forKey:@"schoolId"];
    [self showSchoolLoc:_button2];
    _currentRequestPageNum=1;
    [_paramDic removeObjectForKey:@"pagenumber"];
    [self getData:YES];
}


@end
